package com.baseframe.sys.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baseframe.common.annotation.DataFilter;
import com.baseframe.common.utils.PageUtils;
import com.baseframe.sys.entity.FrameOu;
import com.baseframe.sys.entity.FrameUser;
import com.baseframe.sys.service.IFrameOuService;
import com.baseframe.sys.service.IFrameUserService;
import com.baseframe.sys.service.dao.FrameUserRepository;
import com.baseframe.sys.shiro.DefaultPasswordEncoder;
import com.baseframe.sys.shiro.ShiroUtils;

/**
 * @author mzl
 */
@Service("frameUserService")
public class FrameUserServiceImpl implements IFrameUserService {

	@Autowired
	private FrameUserRepository userRepository;
	@Autowired
	private IFrameOuService sysDeptService;
	@PersistenceContext
	private EntityManager em;

	@Override
	@DataFilter(subDept = true, user = false)
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String) params.get("username");
		int pageSize = Integer.parseInt((String) params.get("limit"));
		int page = Integer.parseInt((String) params.get("page"));
		String sidx = (String) params.get("sidx");
		String order = (String) params.get("order");
		String chql = "select count(1) from FrameUser t where 1=1";
		String hql = "from FrameUser t  where 1=1";
		if (username != null && !username.trim().equals("")) {
			chql += " and t.loginid like '%" + username + "%'";
			hql += " and t.loginid like '%" + username + "%'";
		}
		if (sidx != null && !sidx.equals("")) {
			hql += " order by t." + sidx + " " + order;
		}
		int total = Integer.parseInt(em.createQuery(chql).getSingleResult().toString());

		List<FrameUser> userlist = em.createQuery(hql).setFirstResult((page - 1) * pageSize)
				.setMaxResults(page * pageSize).getResultList();
		// 赋值ouname
		List<FrameOu> oulist = sysDeptService.selectList();
		userlist.forEach(user -> {
			Optional<FrameOu> ouOptional = oulist.stream().filter(temp -> temp.getOuguid().equals(user.getOuguid()))
					.findFirst();
			if (ouOptional.isPresent()) {
				user.setOuname(ouOptional.get().getOuname());
			} else {
			}
		});
		/*
		 * for(FrameUser user:userlist){ FrameOu ou =
		 * sysDeptService.selectById(user.getOuguid());
		 * user.setOuname(ou.getOuname()); }
		 */

		PageUtils p = new PageUtils(userlist, total, pageSize, page);
		return p;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(FrameUser user) {
		user.setUserguid(UUID.randomUUID().toString());
		user.setCreateTime(new Date());
		// sha256加密
		// 改成MD5加密
		// String salt = RandomStringUtils.randomAlphanumeric(20);
		// user.setSalt(salt);
		// user.setPassword(ShiroUtils.sha256(user.getPassword(),
		// user.getSalt()));
		DefaultPasswordEncoder dp = new DefaultPasswordEncoder("MD5");
		String saltPwd = dp.encode(user.getPassword());

		user.setPassword(saltPwd);
		userRepository.save(user);

		// 保存用户与角色关系
		// userRepository.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(FrameUser user) {
		if (StringUtils.isBlank(user.getPassword())) {
			user.setPassword(null);
		} else {
			DefaultPasswordEncoder dp = new DefaultPasswordEncoder("MD5");
			String saltPwd = dp.encode(user.getPassword());

			user.setPassword(saltPwd);
			//user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
		}
		user.setUpdateTime(new Date());
		userRepository.save(user);

		// 保存用户与角色关系
		// sysUserRoleService.saveOrUpdate(user.getUserId(),
		// user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateUser(FrameUser user) {
		// if(StringUtils.isBlank(user.getPassword())){
		// user.setPassword(null);
		// }else{
		// user.setPassword(ShiroUtils.sha256(user.getPassword(),
		// user.getSalt()));
		// }
		user.setUpdateTime(new Date());
		userRepository.save(user);

		// 保存用户与角色关系
		// sysUserRoleService.saveOrUpdate(user.getUserId(),
		// user.getRoleIdList());
	}

	@Override
	public boolean updatePassword(String userId, String password, String newPassword) {
		FrameUser userEntity = new FrameUser();
		userEntity.setPassword(newPassword);
		// 稍后
		return false;
		/*
		 * return this.update(userEntity, new
		 * EntityWrapper<FrameUser>().eq("userguid", userId).eq("password",
		 * password));
		 */
	}

	@Override
	public FrameUser selectById(String userguid) {
		// TODO Auto-generated method stub
		return userRepository.findOne(userguid);
	}

	@Override
	public void delete(String userguid) {
		// TODO Auto-generated method stub
		userRepository.delete(userguid);
	}

	@Override
	public FrameUser findByLoginid(String loginid) {
		// TODO Auto-generated method stub
		return userRepository.findByLoginid(loginid);
	}

}
